<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PostView extends Model
{
    use HasFactory;

    /**
     * 禁用时间戳，因为我们使用自定义的时间字段
     */
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<string>
     */
    protected $fillable = [
        'user_id',
        'post_id',
        'ip_address',
        'user_agent',
        'read_duration',
        'read_progress',
        'viewed_at',
        'last_viewed_at',
        'view_count',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'viewed_at' => 'datetime',
        'last_viewed_at' => 'datetime',
        'view_count' => 'integer',
        'read_duration' => 'integer',
        'read_progress' => 'integer',
    ];

    /**
     * 获取用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 获取文章
     */
    public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class);
    }

    /**
     * 记录或更新浏览历史
     */
    public static function recordView(Post $post, ?User $user = null, array $data = []): self
    {
        $viewData = [
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'last_viewed_at' => now(),
        ];

        if ($user) {
            // 已登录用户，更新或创建记录
            $view = self::firstOrNew([
                'user_id' => $user->id,
                'post_id' => $post->id,
            ]);

            if ($view->exists) {
                // 更新浏览次数和时间
                $view->view_count++;
                $view->last_viewed_at = now();
            } else {
                // 新建记录
                $view->viewed_at = now();
                $view->view_count = 1;
            }
        } else {
            // 游客，基于IP和文章ID查找或创建
            $view = self::firstOrNew([
                'ip_address' => $viewData['ip_address'],
                'post_id' => $post->id,
                'user_id' => null,
            ]);

            if ($view->exists) {
                $view->view_count++;
                $view->last_viewed_at = now();
            } else {
                $view->viewed_at = now();
                $view->view_count = 1;
            }
        }

        // 合并额外数据
        $view->fill(array_merge($viewData, $data));
        $view->save();

        // 更新文章浏览量
        $post->incrementViewCount();

        return $view;
    }

    /**
     * 更新阅读进度
     */
    public function updateReadProgress(int $progress, int $duration): void
    {
        $this->update([
            'read_progress' => min(100, $progress),
            'read_duration' => $this->read_duration + $duration,
        ]);
    }
}